﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RFIDSystem.Common.Helper
{
    /// <summary>
    /// 标签数据结构
    /// </summary>
    public class TagInfo
    {
        /// <summary> 标签UID（通常 4/8/16 字节） </summary>
        public string UID { get; set; }

        /// <summary> 信号强度 (RSSI) </summary>
        public int RSSI { get; set; }

        /// <summary> 温度（如果标签支持温感，否则为 null） </summary>
        public double? Temperature { get; set; }

        /// <summary> 时间戳（设备返回的标签时间，若支持） </summary>
        public DateTime? Timestamp { get; set; }

        /// <summary> 原始数据 </summary>
        public byte[] Raw { get; set; }

        /// <summary>
        /// 从读写器返回的 byte[] 解析为 TagInfo
        /// </summary>
        public static TagInfo Parse(byte[] data)
        {
            if (data == null || data.Length < 8)
                throw new ArgumentException("标签数据长度不足");

            TagInfo tag = new TagInfo();
            tag.Raw = data;

            // 假设格式： [UIDLen][UID...][RSSI][Temp?][Time?]
            int index = 0;
            int uidLen = data[index++];
            if (uidLen + 1 > data.Length)
                throw new Exception("UID 长度错误");

            byte[] uidBytes = new byte[uidLen];
            Array.Copy(data, index, uidBytes, 0, uidLen);
            index += uidLen;

            tag.UID = BitConverter.ToString(uidBytes).Replace("-", "");

            // RSSI
            if (index < data.Length)
                tag.RSSI = data[index++];

            // 温度（假设 2字节，有符号，精度0.1°C）
            if (index + 1 < data.Length)
            {
                short tempRaw = BitConverter.ToInt16(data, index);
                tag.Temperature = tempRaw / 10.0;
                index += 2;
            }

            // 时间戳（假设6字节：YY MM DD HH mm SS）
            if (index + 5 < data.Length)
            {
                int year = 2000 + data[index++];
                int month = data[index++];
                int day = data[index++];
                int hour = data[index++];
                int minute = data[index++];
                int second = data[index++];
                tag.Timestamp = new DateTime(year, month, day, hour, minute, second);
            }

            return tag;
        }

        public override string ToString()
        {
            return $"UID={UID}, RSSI={RSSI}, Temp={Temperature}, Time={Timestamp}";
        }
    }
}
